package com.dflc.controller.SystemController;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.SysDataPermission;
import com.dflc.entity.po.SysUserRole;
import com.dflc.entity.po.TBackLoginUser;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.DataReq;
import com.dflc.entity.req.SysDataReq;
import com.dflc.entity.vo.SysDataPermissionVo;
import com.dflc.mapper.SysDataPermissionMapper;
import com.dflc.mapper.SysUserRoleMapper;
import com.dflc.service.SysDataPermissionService;
import com.dflc.service.TBackLoginUserService;
import com.dflc.utils.EntityUtils;
import com.dflc.utils.PageEntity;
import com.dflc.utils.PageEntityBuilder;
import com.dflc.utils.PageRequestEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据权限Controller控制器
 * @author tqx
 * @site tqx
 * @company 数字涪陵
 */
@RestController
@RequestMapping("/sys/data")
public class SysDataController {

    @Resource
    private TBackLoginUserService tBackLoginUserService;

    @Resource
    private SysDataPermissionService sysDataService;

    @Resource
    private SysDataPermissionMapper sysDataMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;


    /**
     * 获取全部数据权限
     * @author tqx
     * @date 2025/4/25 15:30
     * Description: 获取全部数据权限
     * @return HttpResponseEntity
     */
    @PostMapping("/listAll")
    public HttpResponseEntity listAll(@RequestBody DataReq req){
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            if (ObjectUtils.isEmpty(req.getBusinessName())){
                List<SysDataPermission>  dataList = sysDataService.list(new QueryWrapper<SysDataPermission>().eq("state", CommonConstant.StateActive.Active)
                        .eq("type", req.getType())
                        .eq("unit_id", req.getUnitId())
                        //按照sort进行升序
                        .orderByAsc("sort")
                );
                return HttpResponseEntity.success(dataList);
            }else {
                List<SysDataPermission>  dataList = sysDataService.list(new QueryWrapper<SysDataPermission>().eq("state", CommonConstant.StateActive.Active)
                        .eq("type", req.getType())
                        .eq("unit_id", req.getUnitId())
                        .eq("business_name", req.getBusinessName())
                        //按照sort进行升序
                        .orderByAsc("sort")
                );
                return HttpResponseEntity.success(dataList);
            }
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.getMessage());
        }
    }

    /**
     * 根据条件分页查询数据权限列表
     * @author tqx
     * @param page
     * @date 2025/4/25 15:30
     * Description: 根据条件分页查询数据权限列表
     * @return HttpResponseEntity
     */
    @PostMapping("/list")
    public HttpResponseEntity list(@RequestBody PageRequestEntity page){
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity2 = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity2.getStatus() != 200) {
                return entity2;
            }
            if (ObjectUtils.isEmpty(page.getQuery().get("type"))){
                return HttpResponseEntity.error(500,"请选择数据权限的终端类型！");
            }
            TBackLoginUser tBackLoginUser = (TBackLoginUser)entity2.getData();
            if (!ObjectUtils.isEmpty(tBackLoginUser) && tBackLoginUser.getIsAdmin().intValue() == CommonConstant.BackIsAdmin.Yes.intValue()) {
                // 是超级管理员 按照unitId查询
                SysDataReq req = new SysDataReq();
                req.setCurrent(page.getCurrentPage());
                req.setSize(page.getPageSize());
                if (!org.springframework.util.ObjectUtils.isEmpty(page.getSort()) && page.getSort().get(0).getType()!=null){
                    req.setOrders(EntityUtils.sort(page));
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(page.getQuery().get("name"))){
                    req.setName(page.getQuery().get("name").toString());
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(page.getQuery().get("code"))){
                    req.setCode(page.getQuery().get("code").toString());
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(page.getQuery().get("type"))){
                    req.setType(page.getQuery().get("type").toString());
                }
                if (!org.springframework.util.ObjectUtils.isEmpty(page.getQuery().get("unitId"))){
                    req.setUnitId(Integer.valueOf(page.getQuery().get("unitId").toString()));
                }
                Page<SysDataPermissionVo> page1 = sysDataMapper.pageQuery(req);
                PageEntity entity = PageEntityBuilder.builder()
                        .data(page1.getRecords())
                        .currentPage(page1.getCurrent())
                        .pageSize(page1.getSize())
                        .totalCount(page1.getTotal())
                        .totalPage(page1.getPages())
                        .build();
                return HttpResponseEntity.success(entity);
            }else {
                //不是超级管理员 则不能查询
                return HttpResponseEntity.error(500,"您没有权限查询角色信息！");
            }
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.getMessage());
        }
    }

    /**
     * 添加或者修改
     * @author tqx
     * @param sysData
     * @date 2025/4/25 15:30
     * Description: 添加或者修改
     * @return HttpResponseEntity
     */
    @PostMapping("/save")
    public HttpResponseEntity save(@RequestBody @Valid SysDataPermission sysData){
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            Map<String, Object> params3 = new HashMap<>();
            params3.put("code", sysData.getCode());
            params3.put("type", sysData.getType());
            List<SysDataPermission> list = sysDataMapper.findAllByMap(params3);
            if(ObjectUtils.isEmpty(sysData.getId())){
                if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                    return HttpResponseEntity.error(500, "该数据权限标识码已存在并且有效！");
                }
                sysDataService.save(sysData);
            }else{
                if (!ObjectUtils.isEmpty(list) && list.size() > 0 && list.get(0).getId().intValue()!=sysData.getId().intValue()) {
                    return HttpResponseEntity.error(500, "该数据权限标识码已存在并且有效！");
                }
                sysDataService.updateById(sysData);
            }
            return HttpResponseEntity.success("操作成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.getMessage());
        }
    }

    /**
     * 删除-数据权限
     * @author tqx
     * @param ids
     * @date 2025/4/25 15:30
     * Description: 删除-数据权限
     * @return HttpResponseEntity
     */
    @Transactional
    @GetMapping("/delete/{ids}")
    public HttpResponseEntity delete(@PathVariable(value = "ids")String ids){
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            List<String> strings = Arrays.stream(ids.split(",")).collect(Collectors.toList());
            List<Integer> integerList = new ArrayList<>();
            for (String string : strings) {
                integerList.add(Integer.parseInt(string));
            }

            //查询该数据权限和角色的关系是否有存在的绑定
            Map<String, Object> params2 = new HashMap<>();
            params2.put("dataIds", integerList);
            List<SysUserRole> list2 = sysUserRoleMapper.findAllWxByMap(params2);
            if(!ObjectUtils.isEmpty(list2) || list2.size()>0){
                return HttpResponseEntity.error(500,"选择的数据权限已绑定用户与角色，无法删除！");
            }
            //校验完没有绑定角色 则删除选中的所有数据权限
            Map<String, Object> params = new HashMap<>();
            params.put("ids", integerList);
            List<SysDataPermission> list = sysDataMapper.findAllByMap(params);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0 && list.size()==integerList.size()) {
                for (SysDataPermission sysData : list) {
                    sysData.setState(CommonConstant.StateActive.Deleted);
                }
                sysDataService.saveOrUpdateBatch(list);
                return HttpResponseEntity.success("删除成功！");
            }else if (!ObjectUtils.isEmpty(list) && list.size() > 0 && list.size()<integerList.size()) {
                return HttpResponseEntity.error(500,"选择中的数据有已经删除的数据！");
            }
            return HttpResponseEntity.error(500,"选择的数据不存在！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.getMessage());
        }
    }
}
